// audio.js
/*Page({
  onReady: function (e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio')
  },
  data: {
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
  },
  audioPlay: function () {
    this.audioCtx.play()
  },
  audioPause: function () {
    this.audioCtx.pause()
  },
  audio14: function () {
    this.audioCtx.seek(14)
  },
  audioStart: function () {
    this.audioCtx.seek(0)
  }
})*/

function parseLyric(lrc) {
  var lyrics = lrc.split("\n");
  var lrcObj = {};
  for (var i = 0; i < lyrics.length; i++) {
    var lyric = decodeURIComponent(lyrics[i]);
    var timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
    var timeRegExpArr = lyric.match(timeReg);
    if (!timeRegExpArr) continue;
    var clause = lyric.replace(timeReg, '');
    for (var k = 0, h = timeRegExpArr.length; k < h; k++) {
      var t = timeRegExpArr[k];
      var min = Number(String(t.match(/\[\d*/i)).slice(1)),
        sec = Number(String(t.match(/\:\d*/i)).slice(1));
      var time = min * 60 + sec;
      lrcObj[time] = clause;
    }
  }
  return lrcObj;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canLoadMore:false,//允许加载更多
    songList:[],
    songIdList:[],
    scrollHeight:0,//滚动区域的高度
    size:5,
    offset:0,
    type:1,
    page:1,
    song_id:0,
    music:{},//歌曲对象，当前，包括作者，图片
    playingMusicId:0,
    musicPercent:0,
    musicLrc:'',
    musicLineLrc:''//当前播放的哪一行歌词


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    this.audioCtx=wx.createAudioContext('myAudio');

    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight:res.windowHeight-100
        })
      },
    })

    wx.showLoading({
      title: '数据加载中...',
    })

    wx.request({
      url: 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList',
      data:{
       type:that.data.type,
       size:that.data.size,
       offset:that.data.offset
      },
      header:{
        'content-type':'application/json'
      },
      success:function(res){
       // console.log(res.data)
       var idList=[];
       for(var i=0;i<res.data.song_list.length;i++){
         idList.push(res.data.song_list[i].song_id);
       }
        //console.log(idList)//播放的列表清单
        that.setData({
          songIdList:idList,
          songList:res.data.song_list
        })
        //console.log(that.data.songList,that.data.songIdList);
        wx.hideLoading();
        that.data.page++;
        //页面一打开加载一个音乐
        that.playIdMusic(that.data.songIdList[that.data.playingMusicId])
      }
    })
  },
loadMore(){
  var that=this;
  //canloadmore:防止数据重叠错乱
  if(that.data.canLoadMore===false){
    that.setData({
      canLoadMore:true
    })
  }
  wx.showLoading({
    title: '数据再次加载中...',
  })
  var newOffset=(that.data.page-1)*that.data.size;
  wx.request({
    url: 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList',
    data:{
      type: that.data.type,
      size: that.data.size,
      offset: newOffset
    },
    header:{
      'content-type': 'application/json'
    },
    success:function(res){
      if(res.data.song_list!=null){
        //对原来已经有的数组进行操作
        for(var i=0;i<res.data.song_list.length;i++){
          that.data.songList.push(res.data.song_list[i]);
          that.data.songIdList.push(res.data.song_list[i].song_id);
        }
       // console.log(that.data.songIdList, that.data.songList);
        that.setData({
          songIdList:that.data.songIdList,
          songList:that.data.songList
        })
        that.data.page++;
      }
      wx.hideLoading();
      //不加这个数据可能会不断地往上加，要避免
      setTimeout(()=>{
        canLoadMore:false;
      },1000);
    }
  })
},
  playMusic(e){
    var that=this;
    var url ="http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid="+e.target.dataset.songid;
    // console.log(url)
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      success: function (res) {
        //console.log(res.data)
        that.setData({//当前播放音乐的内容
          music:res.data
        })
        //歌词处理
        wx.request({
          url: res.data.songinfo.lrclink,
          success:function(res){
            //console.log(parseLyric(res.data))
            that.setData({
              musicLrc: parseLyric(res.data)
            })
            that.audioCtx.play();//播放
          }
        })
      }
    })
},
  changeMusicLrc(event){
    //console.log(event);
    var timePosition = Math.floor(event.detail.currentTime);//当前时间点
    var musicPercent = parseInt(event.detail.currentTime/event.detail.duration*100);
    var that= this;
    that.setData({
      musicPercent:musicPercent,
      musicLineLrc: that.data.musicLrc[timePosition]
    })
  },
  playNextMusic(event){
    var that =this;
    var nextMusicPos = that.data.playingMusicId+1;//下标是0123
    var nextMusicSongId = that.data.songIdList(nextMusicPos);
    that.playIdMusic(nextMusicSongId);
    that.setData({
      playingMusicId:nextMusicPos
    })
  },
  playIdMusic(songId){
    var that=this;
    var url='http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid='+songId;
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      success: function (res) {
        //console.log(res.data)
        that.setData({//当前播放音乐的内容
          music: res.data
        })
        //歌词处理
        wx.request({
          url: res.data.songinfo.lrclink,
          success: function (res) {
            //console.log(parseLyric(res.data))
            that.setData({
              musicLrc: parseLyric(res.data)
            })
      //歌词播放要有延迟操作
        setTimeout(()=>{
          that.audioCtx.play();
        },500)
           //that.audioCtx.play();//播放
          }
        })
      }
    })
  }
})









